package org.chen.tomcat;

import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Chen
 * @since 2023/6/9 14:52
 */
public class Tomcat {

    private int port = 8080;

    private HttpServlet dispatcherServlet;

    private boolean started;

    public void setPort(int port) {
        this.port = port;
    }

    public void setDispatcherServlet(HttpServlet dispatcherServlet) {
        this.dispatcherServlet = dispatcherServlet;
    }

    public void start() throws IOException {
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        // Socket连接 TCP
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            started = true;
            while (started) {
                // 阻塞获取请求
                Socket socket = serverSocket.accept();
                //为每一个请求创建一个线程处理请求
                executorService.execute(new SocketProcessor(socket, dispatcherServlet));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void stop() {
        started = false;
    }

}
